<?php
/**
 * Created by PhpStorm.
 * User: lenove
 * Date: 2018/12/12
 * Time: 9:10
 */
include "../config.php";
include "../Status.php";

if($_SERVER["REQUEST_METHOD"] != "POST"){
    print_r(json_encode(Status::$request_error));
    return;
}
$uid = $_POST["uid"]; // 用户id
$gid = $_POST["gid"];//产品id
$gsize = $_POST["size"];//商品尺寸
$gcolor = $_POST["color"];//商品颜色
$gname = $_POST["goodName"];//产品 名称
$gprice = $_POST["price"];//产品价格
$gnum = $_POST["num"];//产品数量
$gimg = $_POST["img"];//产品图片
$totalprice = $_POST["total"];  //产品总金额
//查找该用户买的所有商品
$sql = "SELECT * FROM cart WHERE uid= ? AND g_size=?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("is", $uid,$gsize);
$stmt->execute();
$queryResult = $stmt->get_result();
$flag = false;
while($row = $queryResult->fetch_assoc()){
    if($row["gid"] == $gid && $row["g_size"]==$gsize){
        $flag = true;//找到了,就修改购买数量
        break;
    }
    $stmt->close();
}
//没有找到,就向数据库中插入数据
if(!$flag){
    $sqlInert = "INSERT INTO cart(`uid`,`gid`,`g_name`,`g_size`,`g_color`,`g_num`,`goodpic`,`g_price`,`total_price`)
VALUES(?,?,?,?,?,?,?,?,?);";
    $stmtI = $conn->prepare($sqlInert);
    $stmtI->bind_param("issssisii", $uid, $gid,$gname,$gsize ,$gcolor,$gnum,$gimg,$gprice,$totalprice);
    $stmtI->execute();
    if($stmtI->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功i", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败i", "status" => -1)));
    }
    $stmtI->close();
} else {
    //找到了,则改变购买数量
    $sqlUpdate = "UPDATE cart SET  g_num=g_num+? ,total_price=g_num*g_price WHERE uid=?  and gid=?";
    $stmtU = $conn->prepare($sqlUpdate);
    $stmtU->bind_param("iis", $gnum,$uid,$gid);
    $stmtU->execute();
    if($stmtU->affected_rows >= 1){
        print_r(json_encode(array("msg" => "加入购车成功u", "status" => 1)));
    } else {
        print_r(json_encode(array("msg" => "加入购车失败u", "status" => -1)));
    }
    $stmtU->close();
}
$conn->close();


